<?php

namespace app\v1\model;

use Exception;
use think\exception\ErrorException;
use think\Model;
use think\model\concern\SoftDelete;

class Answer extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    /**
     * @param array $data
     * @return \think\response\Json
     * @throws \Exception
     */
    public function createMore(array $data)
    {
        $this->startTrans();
        try {
            $insert = [];
            if (empty($data)) throw new Exception('数据为空', 2001);
            $user_id = $data['user_id'];
            $answer = $data['answer'];
            $order_no = md5(time());
            foreach ($answer as $item) {
                $insert[] = [
                    'user_id' => $user_id,
                    'question_id' => $item['question_id'],
                    'option_id' => $item['option_id'],
                    'order_no' => $order_no
                ];
            }
            $res = $this->saveAll($insert);
            if (!$res) throw new Exception('答案保存失败', 2002);

            $res = User::update(['name' => $data['name'], 'phone' => $data['phone']],['id' => $user_id]);
            if (!$res) throw new Exception('用户信息更新失败', 2003);
            $this->commit();
        } catch (Exception $errorException) {
            $this->rollback();
            return json(['msg' => $errorException->getMessage(), 'code' => $errorException->getCode()]);
        }
        return json(['msg' => '成功', 'code' => 0]);
    }

    /**
     * 获取所有用户的信息及移民国家
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUsersLastAnswer(int $page = 1,int $limit = 5)
    {
        $arrUserInfo = [];
        // 获取所有用户
        $arrUser = User::where('phone', '>', 0)->page($page)->limit($limit)->select();
        foreach ($arrUser as $user) {
            $id = $user['id'];
            // 获取用户最后一次answer 的订单号
            $last_order_no = Answer::where('user_id', $id)
                ->order('create_time', 'DESC')
                ->value('order_no');
            if (empty($last_order_no)) continue;
            // 获取同一订单的数据
            $last_user_answer = Answer::where(['user_id' => $id, 'order_no' => $last_order_no])->with(['joinQuestion'])->select()->toArray();
            foreach ($last_user_answer as &$answer) {
                $answer['join_option'] = Option::whereIn('id', $answer['option_id'])->select();
            }
            // 需要匹配的题
            $arr_question = [2 => 0, 6 => 0, 7 => 0];
            foreach ($last_user_answer as $item) {
                if (isset($arr_question[$item['question_id']])) {
                    $arr_question[$item['question_id']] = $item['option_id'];
                }
            }
            $option_id_concat = implode(',', $arr_question);
            // 根据逗号连接的选项ID 查询符合要求的移民方法
            $result = QuestionOptionResult::where('option_id_concat', $option_id_concat)->find();
            if (!empty($result)) {
                $arrUserInfo[]  = [
                    'user_info' => $user,
                    'option' => $last_user_answer,
                    'country_intro' => CountryIntro::whereIn('id', $result['country_intro_id_concat'])->select(),
                ];
            }
        }
        return $arrUserInfo;
    }

    public function joinQuestion()
    {
        return $this->belongsTo(Question::class);
    }

    public function joinOption()
    {
        return $this->belongsTo(Option::class);
    }
}
